package org.goyo.main.servlet.captcha;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.goyo.main.servlet.ServiceLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.octo.captcha.service.CaptchaService;
import com.octo.captcha.service.CaptchaServiceException;

public class JCaptchaCodeServlet extends HttpServlet {
	
	private static final long serialVersionUID = 7039924543521287148L;
	
	private static Logger logger = LoggerFactory.getLogger(JCaptchaCodeServlet.class);
	
	
	
	 public void init(ServletConfig servletConfig) throws ServletException {
		 super.init(servletConfig);
		/* ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
			captchaService = (CaptchaService) context.getBean(captchaServiceId);*/
	    }
	 
	 
	    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 
	    	setDisableCacheHeader(response);
			response.setContentType("image/jpeg");

			ServletOutputStream out = response.getOutputStream();
			try {
				
				GMailEngine.getInstance().writeCaptchaImage(  
						request, response);  
				
				/*String captchaId = request.getSession(true).getId();
				BufferedImage challenge = (BufferedImage) captchaService.getChallengeForID(captchaId, request.getLocale());
				String ss =captchaService.getQuestionForID(captchaId, request.getLocale());
				ImageIO.write(challenge, "jpg", out);
				out.flush();*/
			} catch (CaptchaServiceException e) {
				logger.error(e.getMessage(), e);
				response .sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
			} finally {
				out.close();
			}
	    }
	    
	    
		/**
		 * 设置禁止客户端缓存的Header.
		 */
		public static void setDisableCacheHeader(HttpServletResponse response) {
			//Http 1.0 header
			response.setDateHeader("Expires", 1L);
			response.addHeader("Pragma", "no-cache");
			//Http 1.1 header
			response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
		}
}
